<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/common/layuimini/layui.css" media="all">
    <link rel="stylesheet" href="/common/layuimini/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <div class="layui-form layui-form-pane">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">用户账号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="username" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">用户性别</label>
                            <div class="layui-input-inline">
                                <div class="searchSex" id="searchSex"></div>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">邮箱/电话</label>
                            <div class="layui-input-inline">
                                <input type="text" name="emailOrPhone" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">用户角色</label>
                            <div class="layui-input-inline">
                                <div class="userRole" id="userRole"></div>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </div>
            </div>
        </fieldset>

        <table id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            {{# if(d.id != 'admin'){ }}
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
            {{# } }}
        </script>

    </div>
</div>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add" shiro:hasPermission="system:user:add"> 添加 </button>
        <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete" shiro:hasPermission="system:user:delete"> 删除 </button>
<!--        <button class="layui-btn layui-btn-sm layui-btn-primary layui-border-green " lay-event="import" shiro:hasPermission="system:user:import"> 导入 </button>-->
    </div>
</script>
<script type="text/javascript" src="/common/layui/layui.js"></script>
<script type="text/javascript" src="/common/jquery-1.11.3.js"></script>
<script type="text/javascript" src="/common/xm-select/xm-select.js"></script>
<script type="text/javascript" src="/common/blog-ui.js"></script>
<script type="text/javascript">

    //多选下拉框
    var demo1 = xmSelect.render({
        el: '#searchSex',
        radio: true,
        clickClose: true, //点击之后关闭
        theme: {
            color: '#0081ff',
        },
        data: [
            {name: "全部", value: '-1',selected:true},
            {name: "男", value: '1'},
            {name: "女", value: '0'}
        ]
    })

    var demo2 = xmSelect.render({
        el: '#userRole',
        radio: true,
        clickClose: true, //点击之后关闭
        theme: {
            color: '#0081ff',
        },
        data: getRoleSelect()
    })

    layui.use(['form', 'table','util'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            util = layui.util;

        //数据表格实例化
        table.render({
            elem: '#currentTableId',
            url: '/user/admin/table',
            toolbar: '#toolbarDemo',
            id: 'userTable',
            //开启单元格编辑
            escape: true,
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [
                [
                    //复选框
                    {type: 'checkbox'}
                    //用户名列
                    , {field: 'username', title: '用户名', width: 80}
                    //邮箱列
                    , {field: 'email', title: '邮箱', width: 170, sort: true}
                    //个人描述列
                    ,{field: 'description', title: '个人描述', width:230,templet:function (d){
                        if (d.description == null || d.description === ""){
                            return '这个人很懒，什么都没有留下'
                        }else {
                            return d.description;
                        }
                    }}
                    //手机短信业务暂时未开发
                    ,{field: 'phone', title: '电话号', width: 130,sort: true,edit: 'text'}
                    //地址列
                    ,{field: 'address', title: '地址', width: 160,templet: function (d){
                        if (d.address == null || d.address === ""){
                            return "地球"
                        }else {
                            return d.address;
                        }
                    }}
                    ,{field: 'sex', title: '性别', width: 70,templet:function (d){
                        if (d.sex === 1){
                            return '男';
                        }else if (d.sex === 0){
                            return '女'
                        }
                    }}
                    ,{field: 'createTime', title: '创建时间', width: 180,sort: true}
                    ,{fixed: 'right', title:'操作', toolbar: '#currentTableBar', minWidth:150}
                ]
            ],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 10,
            page: true,
            skin: 'line',
            parseData: function(res){//将原始数据解析成 table 组件所规定的数据
            var result;
            if(this.page.curr){
                result = res.data.slice(this.limit*(this.page.curr-1),this.limit*this.page.curr);
            }
            else{
                result=res.data.slice(0,this.limit);
            }
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": result //解析数据列表
            }}
        });

        // 监听表格顶部搜索
        form.on('submit(data-search-btn)', function (data) {
            var sex = demo1.getValue('valueStr');
            var userRoleId = demo2.getValue('valueStr');
            table.reload('userTable', {
                page: {curr: 1}
                , where: {
                    username: data.field.username,
                    sex: sex,
                    emailOrPhone: data.field.emailOrPhone,
                    userRoleId: userRoleId
                }
            }, 'data');
        });

        /**
         * 添加、删除、导入操作
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {
                Pt.openModalBox("添加用户","/user/admin/add")
            } else if (obj.event === 'delete') {  // 监听删除操作
                //获取复选框选中的数据
                var allData = table.checkStatus('userTable').data;
                if (allData.length === 0) {
                    layer.msg('请选择删除的数据');
                    return;
                }
                if (allData.length === 1) {
                    if (allData[0]["type"] === 'all'){
                        layer.msg('本条数据您没有权限删除');
                        return;
                    }
                }
                //判断是否是管理员
                for (var i = 0; i < allData.length; i++) {
                    if (allData[i]["type"] === 'all'){
                        layer.msg('第'+(i+1)+'个数据您没有权限删除');
                        return;
                    }
                }
                //获取选中数据id
                var deleteIds = getTableIds();

                //询问框
                layer.confirm('确定删除这'+(deleteIds.length)+'条数据吗?', {
                    btn: ['确定','再想想'] //按钮
                }, function(){
                    $.ajax({
                        url: "/user/table/deleteByIds",
                        type: "post",
                        dataType: "json",
                        //必须加上这段代码
                        contentType : "application/json;charsetset=UTF-8",
                        data: JSON.stringify(deleteIds),
                        success: function (res){
                            if (res.state){
                                layer.msg('删除成功',function (){
                                    //执行搜索重载
                                    table.reload('userTable', {
                                        page: {curr: 1}
                                    });
                                });
                            }else{
                                layer.msg(res.msg);
                            }
                        }
                    })
                });
            }else if (obj.event === 'import') {  // 监听导入
                parent.layer.open({
                    type: 2,
                    title: '导入用户',
                    shadeClose: true,
                    shade: false,
                    maxmin: true,
                    area: ['700px', '400px'],
                    content: '/user/table/import'
                });
            }
        });

        /**
         * 获取用户表格所有id
         */
        function getTableIds() {
            var ids = []
            var dataLen = table.checkStatus('userTable').data.length;
            for (var i = 0; i < dataLen; i++) {
                ids[i] = table.checkStatus('userTable').data[i]["id"]
            }
            return ids;
        }


        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });


        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                const url = "/user/admin/user-edit?userId="+data.id;
                Pt.openModalBox("编辑用户",url);
            } else if (obj.event === 'delete') {
                layer.confirm('真的删除行么', function (index) {
                    obj.del();
                    layer.close(index);
                });
            }
        });
    });

    /**
     * 获取角色的xm-select下拉选
     * @param
     * @return
     */
    function getRoleSelect(){
        var data;
        $.ajax({
            url: "/user/admin/getRoleSelect",
            type: "get",
            async: false,
            success(res){
                if (res.state){
                    data = res.data;
                }
            },
            error(res){
                console.log(res);
            }
        })
        return data;
    }
</script>

</body>
</html>
